package com.remote.core;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.Scanner;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;

public class XShellClient {

	public static void main(String[] args) {

		try {
			String hostname = "122.51.211.33";
			String username = "root";
			String password = "eyIN2zKWs2x";

			Session session = null;
			Connection conn = null;

			System.out.println("connection 122 start...");

			// 建立连接
			conn = new Connection(hostname, 22);
			// 连接
			ConnectionInfo info = conn.connect();

			// 授权
			boolean isAuthenticate = conn.authenticateWithPassword(username, password);
			if (isAuthenticate) {

				// 打开连接
				session = conn.openSession();
				// 打开bash
				session.requestPTY("bash");
//	              session.requestPTY("xterm", 90, 30, 0, 0, null);

				session.startShell();

				// 启动多线程，来获取我们运行的结果
				// 第一个参数 输入流
				// 第二个参数 输出流，这个直接输出的是控制台
				ReadThread is = new ReadThread(session.getStdout(), new PrintStream(System.out));
				new Thread(is).start();

				// 启动线程2，我
				ReadThread error = new ReadThread(session.getStderr(), new PrintStream(System.out));
				new Thread(error).start();

				Scanner scanner = new Scanner(System.in);
				while (true) {
					String commondStr = scanner.nextLine();
					// 输出流
					BufferedWriter out = new BufferedWriter(new OutputStreamWriter(session.getStdin(), "utf-8"));
					out.write(commondStr + "\n");
					out.flush();

					if (commondStr.equals("exit")) {
						// 停止线程
						is.stopThread();
						session.close();
						conn.close();
						scanner.close();
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
